//
//  SCPushPopTransition.m
//  SCFoundationKit
//
//  Created by Chao Sheng on 2023/10/23.
//

#import "SCPushPopTransition.h"
#import "UIView+SCBaseExt.h"

@implementation SCPushPopTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return self.transitionDuration > 0 ? self.transitionDuration : 0.3;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    /// 转场过渡容器， 如果是push ,A->B, fromVC是A，toVC是B，如果是Pop，fromVC是B，toVC是A。
    UIView *containView = [transitionContext containerView];
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *fromView = fromVC.view;
    
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *toView = toVC.view;
    
    CGRect fromFrame = CGRectZero;
    CGRect toFrame = CGRectZero;
    if(self.isPush) {
        [containView addSubview:fromView];
        [containView addSubview:toView];

        fromFrame = containView.bounds;
        fromView.frame = fromFrame;

        toFrame = CGRectMake(containView.sc_width, 0, containView.sc_width, containView.sc_height);
        toView.frame = toFrame;

    } else {
        [containView addSubview:toView];
        [containView addSubview:fromView];
        
        fromFrame = containView.bounds;
        fromView.frame = fromFrame;
        toView.frame = fromFrame;
        
        toFrame = CGRectMake(containView.sc_width, 0, containView.sc_width, containView.sc_height);
    }
    
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        if(self.isPush) {
            toView.frame = fromFrame;
        } else {
            fromView.frame = toFrame;
        }
    } completion:^(BOOL finished) {

        /// 设置 transitionContext 通知系统动画执行完毕
        BOOL cancel = [transitionContext transitionWasCancelled];
        [transitionContext completeTransition:!cancel];
    }];
    
}

- (UIImage *)screenShotImage:(UIView *)view {
    //参数： 区域大小、非透明度（需要半透明效果，需传NO）,屏幕密度
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    } else {
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return viewImage;
}

@end
